#include "WindowForm.hpp"
#include "Control.hpp"
#include "Button.hpp"
#include "Label.hpp"
#include <map>
#include "Application.hpp"
using namespace NAMESPACENAME;
extern std::map<HWND, Control*> __mapWindows;
WindowForm::WindowForm(const Rectangle& rect, String title, ContainerControl* parent) :
	ContainerControl(rect, parent)
{
	auto p(title.UnsafeGetString());
	hWnd = CreateWindowExW(
		0,
		L"MainWindow",
		p,
		WS_OVERLAPPEDWINDOW,
		rect.x,
		rect.y,
		rect.width,
		rect.height,
		parent ? parent->WindowHandle() : nullptr,
		nullptr,
		Application::GetInstance(),
		nullptr
	);
	delete[] p;
	if (hWnd)
		__mapWindows.emplace(std::make_pair(hWnd, this));
	else
		throw std::exception("Create WindowForm Failed!", 0);
}
void WindowForm::OnDestroy()
{
	ContainerControl::OnDestroy();
}
void WindowForm::OnClose()
{
	ContainerControl::OnClose();
	DestroyWindow(hWnd);
}
void WindowForm::OnNcPaint(HRGN hRgn)
{
	DefWindowProcW(hWnd, WM_NCPAINT, (WPARAM)hRgn, 0);
	/*HDC hDC;
	hDC = GetDCEx(hWnd, hRgn, DCX_WINDOW | DCX_INTERSECTRGN);
	RECT rect;
	rect.left = 0;
	rect.right = GetSystemMetrics(SM_CYCAPTION);
	rect.top = 0;
	rect.bottom = 40;
	// Paint into this DC
	//DrawCaption(hWnd, hDC, &rect, DC_ACTIVE | DC_GRADIENT);
	ReleaseDC(hWnd, hDC);*/
}
void WindowForm::OnCommand(UINT message, UINT id, Control* control)
{
	if (control)
		control->OnCommand(message, id, nullptr);
}
void WindowForm::Visibility(enum class Visibility vis)
{
	ContainerControl::Visibility(vis);
	switch (vis)
	{
	case Visibility::Visible:
		::ShowWindowAsync(hWnd, SW_NORMAL);
		break;
	case Visibility::Hidden:
		::ShowWindowAsync(hWnd, SW_MINIMIZE);
		break;
	case Visibility::Maximize:
		::ShowWindowAsync(hWnd, SW_MAXIMIZE);
		break;
	}
}
void WindowForm::OnLoad()
{
}
void WindowForm::OnUnLoad()
{
}
void WindowForm::OnPaint()
{
	PAINTSTRUCT ps;
	HDC hDC = BeginPaint(hWnd, &ps);
	PaintEventArgs e;
	e.clipRect = ps.rcPaint;
	e.hDC = hDC;
	onPaint(this, e);
	EndPaint(hWnd, &ps);
}
void WindowForm::OnSize(SizeEventArgs& e)
{
	ScrollableControl::OnSize(e);
	switch (e.sizeType)
	{
	case SizeEventArgs::SizeType::Maximized:
		visibility = Visibility::Maximize;
		break;
	case SizeEventArgs::SizeType::Restored:
		visibility = Visibility::Visible;
		break;
	case SizeEventArgs::SizeType::Minimized:
		visibility = Visibility::Hidden;
		break;
	}
}
void WindowForm::OnSizing(SizingEventArgs& e)
{
	ScrollableControl::OnSizing(e);
}